from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        # 创建一个虚拟头节点
        home = ListNode()
        # 初始化 current 指针指向虚拟头节点
        current = home

        # 遍历两个链表
        while list1 or list2:
            if list1 and (not list2 or list1.val < list2.val):
                current.next = list1
                list1 = list1.next
            elif list2:
                current.next = list2
                list2 = list2.next
            # 移动 current 指针到下一个节点
            current = current.next

        # 返回合并后链表的头节点
        return home.next

    def iteration(self, listNode):
        cur = listNode
        while cur:
            print(cur.val, end=' -> ')
            cur = cur.next
        print("None")

if __name__ == '__main__':
    s = Solution()
    head1 = ListNode(1)
    head1.next = ListNode(2)
    head1.next.next = ListNode(3)
    head2 = ListNode(4)
    head2.next = ListNode(5)
    head2.next.next = ListNode(6)

    s.iteration(head1)
    print()
    s.iteration(head2)
    home = s.mergeTwoLists(head1, head2)
    print()
    s.iteration(home)